from flask import g
from flask import request
from flask import session, jsonify
from info import redis_store
from info.models import User, News, Category
from info.modules.index import index_blue
import logging
from flask import current_app,render_template

from info.utils.commons import user_login_data
from info.utils.response_code import RET







# 分页获取函数
@index_blue.route('/newslist')
def newslist():
    #1获取参数
    cid = request.args.get("cid","1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")
    #2参数类型转换
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 10
    #3分页查询
    try:

        # if cid == "1":
        #     paginate = News.query.filter().order_by(News.create_time.desc()).paginate(page,per_page,False)
        # else:
        #     paginate = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(page,per_page,False)

        # filters = ""
        # if cid != "1":
        #     filters = (News.category_id == cid)
        # paginate = News.query.filter(filters).order_by(News.create_time.desc()).paginate(page, per_page, False)

        filters = []
        if cid != "1":
            filters.append(News.category_id == cid)
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)

    except Exception as e:
       current_app.logger.error(e)
       return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")
    #4获取到分页对象中的属性,总页数,当前页,当前页的对象
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items
    #5将对象列表转成字典列表
    news_list = []
    for news in items:
        news_list.append(news.to_dict())
    #6携带数据,返回响应
    return jsonify(errno=RET.OK,errmsg="获取新闻成功",totalPage=totalPage,currentPage=currentPage,newsList=news_list)




@index_blue.route('/',methods=["GET","POST"])
@user_login_data
def index():
   # 获取用户的登陆信息
   # user_id = session.get("user_id")
   # # 通过uesr_id取出用户对象
   # user = None
   # if user_id:
   #     try:
   #         user = User.query.get(user_id)
   #     except Exception as e:
   #         current_app.logger.error(e)
   # 根据热门新闻,根据点击量.查询前十条新闻
   try:
       news = News.query.order_by(News.clicks.desc()).limit(10).all()
   except Exception as e:
       current_app.logger.error(e)
       return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")
   # 将新闻对象列表转成字典
   news_list = []
   for item in news:
       news_list.append(item.to_dict())

   # 查询所有分类
   try:
       categories = Category.query.all()
   except Exception as e:
       current_app.logger.error(e)
       return jsonify(errno=RET.DBERR,errmsg="获取分类失败")
   # 将分类对象列表转成字典列表
   category_list = []
   for categroy in categories:
       category_list.append(categroy.to_dict())





   data = {
       "user_info":g.user.to_dict() if g.user else "",
       "news_list":news_list,
       "category_list":category_list
   }
   return render_template("news/index.html",data=data)



@index_blue.route('/avicon.ico')
def get_web_logo():

   return current_app.send_static_file('news/favicon.ico')